import { PlusOutlined } from "@ant-design/icons";
import { ActionType, ProColumns, ProTable } from "@ant-design/pro-components";
import { Button, Form, Input, message, Modal, Space } from "antd"
import { memo, useRef, useState } from "react";
import { createUser, deleteUser, listUsers, updateUser } from "../api/request";
import { formatTime } from "../utils/utils";


const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
};

const User = () => {
    const actionRef = useRef<ActionType>();
    const [visibleCreate, setvisibleCreate] = useState(false);
    const [type, setType] = useState<'create' | 'update'>('create');
    const [form] = Form.useForm();
    const [data, setData] = useState<UserData>(null!)
    const [loadding, setLoading] = useState<boolean>(null!)
    const formRef = useRef(null!)
    const [passwordVisible, setPasswordVisible] = useState(false);

    const columns: ProColumns<UserData>[] = [
        {
            title: '用户名',
            dataIndex: 'userName',
            search: false,
            width: 240,
        },
        {
            title: '名称',
            dataIndex: 'nickName',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            width: 230,
            search: false
        },
        {
            title: '电话',
            dataIndex: 'phone',
            width: 230,
            search: false
        },
        {
            title: '创建时间',
            dataIndex: 'createdTime',
            search: false,
            width: 230,
            render: (text, record,) => {
                return formatTime(record.createdTime)
            }
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            width: 230,
            render: (text, record, _, action) => [
                <Button type="link" style={{ padding: 0 }} onClick={() => {
                    setType('update')
                    setvisibleCreate(true)
                    form.setFieldValue('password', '')
                    setData(record)
                    form.setFieldsValue(record)
                }}>
                    修改
                </Button>,
                <Button type="link" style={{ padding: 0 }} onClick={() => {
                    Modal.confirm({
                        title: '删除',
                        content: '是否删除',
                        onOk: async () => {
                            await deleteUser(record.id)
                            actionRef.current?.reload()
                            Modal.destroyAll();
                            message.success("删除成功")
                        }
                    })
                }}>
                    删除
                </Button>
            ],
        }
    ]

    return <div>
        <ProTable<UserData>
            columns={columns}
            actionRef={actionRef}
            headerTitle="字典"
            cardBordered
            editable={{
                type: 'multiple',
            }}
            formRef={formRef}
            rowKey="id"
            options={{
                setting: {
                    listsHeight: 400,
                },
            }}
            pagination={{
                pageSize: 5
            }}
            request={async (params) => await listUsers(params)}
            dateFormatter="string"
            toolBarRender={() => [
                <Button
                    key="button"
                    icon={<PlusOutlined />}
                    onClick={() => (setvisibleCreate(true), setType("create"), form.resetFields())}
                    type="primary"
                >
                    新建
                </Button>
            ]}
        />

        <Modal title={type == "create" ? "新建" : "修改"}
            open={visibleCreate}
            confirmLoading={loadding}
            onOk={() => {
                form.validateFields().then(async (values) => {
                    console.log("values", values)
                    setLoading(true)
                    if (type == "create") {
                        const result = await createUser(values)
                        if (result.code == 200) {
                            message.success('创建成功')
                            setLoading(false)
                        } else {
                            message.error(result.msg)
                        }
                    } else {
                        const result = await updateUser({ id: data.id, ...values })
                        if (result.code == 200) {
                            message.success('修改成功')
                            setLoading(false)
                        } else {
                            message.error(result.msg)
                        }
                    }
                    setLoading(false)
                    actionRef.current?.reload()
                    setvisibleCreate(false)
                })
            }}
            onCancel={() => setvisibleCreate(false)}
            onClose={() => setvisibleCreate(false)}>
            <Form
                {...layout}
                form={form}
                style={{ maxWidth: 600 }}
                className="mt-6"
            >
                <Form.Item name="userName" label="用户名" rules={[{ required: true }]}>
                    <Input autoComplete="off" placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item name="password" label="密码" rules={
                    type == "create" ? [{ required: true, message: '请输入密码' },
                    {
                        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
                        message: '密码包含大小写字母、数字和特殊字符，且不少于8位'
                    }] :
                        [{
                            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
                            message: '密码包含大小写字母、数字和特殊字符，且不少于8位'
                        }]}>
                    <Input.Password
                        placeholder="请输入密码"
                    />
                </Form.Item>
                <Form.Item name="nickName" label="名称" rules={[{ required: true }]}>
                    <Input autoComplete="off" placeholder="请输入名称" />
                </Form.Item>
                <Form.Item name="email" label="邮箱" rules={[
                    {
                        pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/,
                        message: '邮箱格式不正确'
                    }
                ]}>
                    <Input autoComplete="off" placeholder="请输入邮箱" />
                </Form.Item>
                <Form.Item name="phone" label="手机" rules={[
                    {
                        pattern: /^1[3-9]\d{9}$/,
                        message: '请输入有效的手机号码'
                    }
                ]}>
                    <Input autoComplete="off" placeholder="请输入手机号" />
                </Form.Item>
            </Form>
        </Modal>
    </div>
}

export default memo(User)